import { getUserCouponList } from '@/service'
import { arrayGroupBy } from '@/common/utils'
import {  CouponStatusEnum, CouponStatusMap,CouponBatchStatusEnum,CouponBatchStatusMap } from '@/utils/enum'
import { Popup } from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import { useRequest } from 'ahooks'
import classNames from 'classnames'
import dayjs from 'dayjs'
import React, { useEffect, useImperativeHandle, useMemo, useState } from 'react'
import styles from './index.module.less'

type CouponSelectPopPropsType = {
  cinemaCode?: number | string;
  moveCode?: number | string;
  hall?: string;
  showTime?: string;
  showId?: string;
  version?: string;
  originPrice?: number;
  publishPrice?: number;
  fastTicket?: boolean;
  buyNum?: number;

  storeId?: number | string;
  brandId?: number | string;
  productId?: number | string;
  totalOfficialPrice?: number | string;
  orderQuantity?: number;
  selectedCouponCode: Coupon.ListItem['couponCode'] | undefined;
  onSelect: (item: Coupon.ListItem | undefined) => void;
  onCouponListGroupChange?: (groupData: [CouponBatchStatusEnum, Coupon.ListItem[]][]) => void
}
export type CouponSelectPopRefType = {
  open: () => void,
}

// 暂时只有电影品牌使用到，后续会支持点餐品牌
function CouponSelectPop(props: CouponSelectPopPropsType, ref: React.ForwardedRef<CouponSelectPopRefType>) {
  const { cinemaCode, moveCode, hall, showTime, showId, version, originPrice, publishPrice,fastTicket,buyNum , selectedCouponCode, onSelect, onCouponListGroupChange } = props
  const [visible, setVisible] = useState(false)
  
  const couponListApi = useRequest(async() => { 
    return (await getUserCouponList({
      cinemaCode, moveCode, hall, showTime, showId, version, originPrice, publishPrice, buyNum,
    })).list
      .sort((a, b) => b.batchValue - a.batchValue)
  }, {
    ready: true,
    refreshDeps: [originPrice, publishPrice]
  })

  const couponListGroup = useMemo(() => {
    const groupMap = arrayGroupBy<Coupon.ListItem, CouponBatchStatusEnum>(couponListApi.data || [], item => item.couponBatchStatus, CouponBatchStatusEnum.enable)
    return Array.from(groupMap).sort((a, b) => b[0] - a[0])
  }, [couponListApi.data])

  useEffect(() => { 
    onCouponListGroupChange?.(couponListGroup)
  }, [couponListGroup])

  useImperativeHandle(ref, () => ({
    open: () => setVisible(true),
  }))

  return (
    <Popup
      visible={visible}
      onClose={() => setVisible(false)}
      position='bottom'
      round
      lockScroll
      className={styles.couponSelectPop}
    >
      <div className={styles.close} onClick={() => setVisible(false)}></div>
      <div className={styles.popTitle} onClick={() => setVisible(false)}>优惠券</div>
      <div className={styles.popContent}>
        {couponListGroup.length == 0 && <div className={styles.statusItem}><div className={styles.statusTitle}>暂无优惠券</div></div>}
        {couponListGroup.map(([key, items]) => {
          return (
            <div key={key.toString()} className={styles.statusItem}>
              <div className={styles.statusTitle}>
                {CouponBatchStatusMap.get(key)}优惠券（{items.length}）
              </div>
              {items.map(item => {
                const { couponCode, batchValue, useThreshold, seatThreshold, couponName, startValidTime, endValidTime, couponStatus,couponBatchStatus, remark, couponType } = item
                const isDisable = couponBatchStatus === CouponBatchStatusEnum.disable || couponStatus !== CouponStatusEnum.Usable || fastTicket
                const isSelect = couponCode === selectedCouponCode
                return (
                  <div
                    key={couponCode}
                    className={classNames(styles.card, { [styles.disabled]: isDisable })}
                    onClick={() => { 
                      if (isDisable) return Taro.showToast({ title: remark ? remark : (couponStatus == CouponStatusEnum.Usable && fastTicket ? '当前快票' : CouponStatusMap.get(couponStatus)) + '不可用', icon: 'none' })
                      onSelect(isSelect ? undefined : item)
                    }}
                  >
                    <div className={styles.priceBox}>
                      {couponType !== 1 && <div className={styles.batchValueBox}>
                        ￥<div className={styles.batchValue}>{batchValue}</div>
                      </div>
                      }
                      <div className={styles.batchRule}>
                      {seatThreshold === 0 ? (useThreshold === 0 ? `无门槛` : `满${useThreshold}可用`) : `满${seatThreshold}张可用`}
                      </div>
                    </div>
                    <div className={styles.dashedLine}></div>
                    <div className={styles.infoBox}>
                      <div className={styles.title}>{couponName}</div>
                      {/* <div className={styles.validDate}>
                      {couponCode}
                      </div> */}
                      <div className={styles.validDate}>
                        {dayjs(startValidTime).format("YYYY.MM.DD")}
                        ~
                        {dayjs(endValidTime).format("YYYY.MM.DD")}
                      </div>
                      {isDisable && <div className={styles.status}>
                        <div className={styles.tag}>不可用{couponStatus == CouponStatusEnum.Usable && fastTicket ? '：当前快票' : ''}</div>
                        {remark}
                      </div>}
                    </div>
                    {!isDisable && <div className={classNames(styles.select, { [styles.selected]: isSelect })}> </div>}
                  </div>
                )
              })}
            </div>
          )
        })}
      </div>
      <div className={styles.popFooter}>
        <div className={styles.btn} onClick={() => setVisible(false)}>确定</div>
      </div>
    </Popup>
  )
}

export default React.forwardRef<CouponSelectPopRefType, CouponSelectPopPropsType>(CouponSelectPop)